﻿using System.Security.Cryptography;
using System.Text;

namespace WMS.FC.Infrastructure.Common
{
    public class EncryptHelper
    {
        public const string KEY = "123456789abcdefghijklmnopqrstuvwxyz";
        public const string IV = "123456789abcdefghijklmnopqrstuvwxyz";

        /// <summary>
        /// 加密
        /// </summary>
        /// <param name="target"></param>
        /// <param name="key"></param>
        /// <param name="iv"></param>
        /// <returns></returns>
        public static string Encrypt(string target, string key = KEY, string iv = IV)
        {
            using var aesAlg = Aes.Create();
            aesAlg.Key = Encoding.UTF8.GetBytes(key[..32]);
            aesAlg.IV = Encoding.UTF8.GetBytes(iv[..16]);
            var encryptor = aesAlg.CreateEncryptor();
            using var msEncrypt = new MemoryStream();
            using var csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write);
            using (var swEncrypt = new StreamWriter(csEncrypt))
            {
                swEncrypt.Write(target);
            }

            return Convert.ToBase64String(msEncrypt.ToArray());
        }

        /// <summary>
        /// 解密
        /// </summary>
        /// <param name="target"></param>
        /// <param name="key"></param>
        /// <param name="iv"></param>
        /// <returns></returns>
        public static string Decrypt(string target, string key = KEY, string iv = IV)
        {
            var targetBytes = Convert.FromBase64String(target);
            using var aesAlg = Aes.Create();
            aesAlg.Key = Encoding.UTF8.GetBytes(key[..32]);
            aesAlg.IV = Encoding.UTF8.GetBytes(iv[..16]);
            var decryptor = aesAlg.CreateDecryptor();

            using var msEncrypt = new MemoryStream(targetBytes);
            using var csEncrypt = new CryptoStream(msEncrypt, decryptor, CryptoStreamMode.Read);
            using var srEncrypt = new StreamReader(csEncrypt);
            return srEncrypt.ReadToEnd();
        }

        /// <summary>
        /// 前端base64加密
        /// </summary>
        /// <param name="code_type">utf-8</param>
        /// <param name="code">前端加密后字符串</param>
        /// <returns></returns>
        public static string DecodeBase64(string code_type, string code)
        {
            byte[] bytes = Convert.FromBase64String(code);
            string decode;
            try
            {
                decode = Encoding.GetEncoding(code_type).GetString(bytes);
            }
            catch
            {
                decode = code;
            }
            return decode;
        }
    }
}
